package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.tools.Constants;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Auther: liyuxuan
 * @Date:2021/11/16 - 11 - 16 - 9:18
 */
@Log4j
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    public String list(Model model){
        List<Role> roleList = roleService.getAllRoleList();
        model.addAttribute("rList",roleList);
        return "/jsp/rolelist";
    }
    @GetMapping("/toAdd")
    public String toAdd(){
        return "/jsp/roleadd";
    }
    @PostMapping("/add")
    public String add(Role role, HttpSession session){
        role.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        role.setCreationDate(new Date());
        if(roleService.add(role)){
            return "redirect:/role/list";
        }
        return "/jsp/rolelist";
    }
    @GetMapping("/toModify/{id}")
    public String toModify(@PathVariable String id,Model model){
        Role role = roleService.getRoleById(id);
        model.addAttribute(role);
        return "/jsp/roleupdate";
    }
    @PostMapping("/modify")
    public String modify(Role role,String id,HttpSession session){
        role.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        role.setModifyDate(new Date());
        if(roleService.update(role,id)){
            return "redirect:/role/list";
        }
        return "/jsp/roleupdate";
    }
    @ResponseBody
    @GetMapping("/roleDel/{id}")
    public Object roleDel(@PathVariable String id,Model model){
        if(roleService.getUserById(id)){
            if(roleService.del(id)){
                return model.addAttribute("delResult","true");
            }
        }
        return model.addAttribute("delResult","false");
    }
    @ResponseBody
    @RequestMapping("/getRoleByCode/{code}")
    public Object getRoleByCode(@PathVariable String code){
        if(roleService.getRoleByCode(code)){
            return true;
        }
        return false;
    }
}
